package com.zy.multiredis.controller;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zy.multiredis.config.LazyInject;
import com.zy.multiredis.config.MultiRedisTemplateMap;

@RestController
public class DemoController {

    @Autowired
    private RedisTemplate redisTemplate;

    @LazyInject(injectName = "redis1")
    private RedisTemplate redisTemplate1;

    @LazyInject(injectName = "redis2")
    private RedisTemplate redisTemplate2;

    @Autowired
    private Map<String, RedisTemplate> map;

    @Autowired
    private MultiRedisTemplateMap multiRedisTemplateMap;

    @Autowired
    ApplicationContext applicationContext;

    @RequestMapping("/add")
    public String add() {
        // 单独注入
        redisTemplate.opsForValue().set("date", new Date().getTime() + "");
        redisTemplate1.opsForValue().set("date", new Date().getTime() + "");
        redisTemplate2.opsForValue().set("date", new Date().getTime() + "");

        // 通过容器Map注入
        for (Map.Entry<String, RedisTemplate> entry : map.entrySet()) {
            entry.getValue().opsForValue().set("date", new Date().getTime() + "");
        }

        // 通过multiRedisTemplateMap对象获取
        for (Map.Entry<String, RedisTemplate> entry : multiRedisTemplateMap.getRedisTemplates().entrySet()) {
            entry.getValue().opsForValue().set("date", new Date().getTime() + "");
        }

        return "execute add ok";
    }

    @RequestMapping("/get")
    public String get() {
        // 单独注入
        System.out.println(redisTemplate.opsForValue().get("date"));
        System.out.println(redisTemplate1.opsForValue().get("date"));
        System.out.println(redisTemplate2.opsForValue().get("date"));

        // 通过容器Map注入
        for (Map.Entry<String, RedisTemplate> entry : map.entrySet()) {
            System.out.println(entry.getValue().opsForValue().get("date"));
        }

        // 通过multiRedisTemplateMap对象获取
        for (Map.Entry<String, RedisTemplate> entry : multiRedisTemplateMap.getRedisTemplates().entrySet()) {
            System.out.println(entry.getValue().opsForValue().get("date"));
        }

        return "execute get ok";
    }
}
